package com.project.smarthome.login.presenter;

import android.graphics.Bitmap;
import android.net.Uri;

import com.project.smarthome.SmartApplication;
import com.project.smarthome.base.BasePresenter;
import com.project.smarthome.login.LoginContract;
import com.project.smarthome.login.model.NameAndPhone;
import com.sds.sdk.android.sh.common.util.TextUtils;
import com.sds.smarthome.business.domain.UserService;
import com.sds.smarthome.business.domain.entity.LoginResult;
import com.sds.smarthome.business.domain.service.DomainFactory;
import com.sds.smarthome.foundation.DataSourceFactory;
import com.sds.smarthome.foundation.util.XLog;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.sds.smarthome.foundation.DataSourceFactory.getAppCache;

/**
 * Created by L on 2016/5/18.
 */
public class LoginPresenter extends BasePresenter implements LoginContract.Presenter {

    private static final String LAST_LOGIN_USER = "last_login_user";
    private static final String LOGGED_IN_USER_LIST = "login_in_user_list";
    private final LoginContract.View mLoginView;
    private final UserService mUserService;

    public LoginPresenter(LoginContract.View loginView) {
        this.mLoginView = loginView;
        mUserService = DomainFactory.getUserService();
    }

    @Override
    public void init() {
        String username = getAppCache().getString(LAST_LOGIN_USER);
        if (username != null) {
            mLoginView.showUserName(username);
        }
        List<NameAndPhone> phoneList = (List<NameAndPhone>) DataSourceFactory.getAppCache().getObject(LOGGED_IN_USER_LIST);
        mLoginView.showLoginHistory(phoneList);
    }

    @Override
    public void toLogin(final String phoneNum, final String password) {

        mLoginView.showLoading("登录中");

        Observable observable = Observable.create(new ObservableOnSubscribe<LoginResult>() {
            @Override
            public void subscribe(ObservableEmitter<LoginResult> e) throws Exception {
                LoginResult result = mUserService.toLogin(phoneNum, password);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                e.onNext(result);
                XLog.e("login");
                if (result != null && result.isSuccess()) {
                    getAppCache().putString(LAST_LOGIN_USER, phoneNum);
                    if (!TextUtils.isEmpty(result.getAvatarUrl())) {
                        RequestCreator requestCreator = Picasso.with(SmartApplication.getContext()).load(Uri.parse(result.getAvatarUrl()));
                        try {
                            Bitmap avatarIcon = requestCreator.get();
                            getAppCache().putImageFile(phoneNum, avatarIcon);
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }

                    List<NameAndPhone> phoneList = (List<NameAndPhone>) DataSourceFactory.getAppCache().getObject(LOGGED_IN_USER_LIST);
                    if (phoneList == null) {
                        phoneList = new ArrayList<>();
                    }
                    NameAndPhone exist = null;
                    for (NameAndPhone bean : phoneList) {
                        if (bean.getPhone().equals(phoneNum)) {
                            exist = bean;
                            break;
                        }
                    }
                    if (exist != null) {
                        phoneList.remove(exist);
                        exist = null;
                    }
                    exist = new NameAndPhone(result.getNickName(), result.getUsername());
                    exist.setImageFile(getAppCache().getImageFile(phoneNum).getAbsolutePath());
                    phoneList.add(0, exist);
                    getAppCache().putObject(LOGGED_IN_USER_LIST, phoneList);
                }
                XLog.e("login");
            }

        });
        Disposable subscription = observable.
                subscribeOn(getJobExecutor()).
                observeOn(getUiExecutor()).
                subscribe(new Consumer<LoginResult>() {
                    @Override
                    public void accept(LoginResult result) throws Exception {
                        mLoginView.hideLoading();
                        if (result != null) {
                            if (result.isSuccess()) {
                                mLoginView.loginSuccessToMain();
                            } else {
                                mLoginView.showLoginError(getCloudErrorDesc(result.getError() == null ? -1 : result.getError().getErrorCode()));
                            }
                        }
                    }

                });
        addSubscription(subscription);
    }


    @Override
    public void destroy() {
        super.destroy();
    }
}
